<template>
  <div class="history-container">
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <h2>历史记录</h2>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索历史记录..."
            prefix-icon="el-icon-search"
            clearable
            class="search-input"
          />
        </div>
      </template>

      <el-tabs v-model="activeTab" class="history-tabs" @tab-click="handleTabClick">
        <el-tab-pane label="辩论历史" name="debate">
          <el-empty v-if="filteredDebateHistory.length === 0" description="暂无辩论历史记录" />
          
          <div v-else class="history-list">
            <el-card 
              v-for="(item, index) in filteredDebateHistory" 
              :key="index" 
              class="history-item"
              :class="{ 'selected': selectedSession?.id === item.id }"
              @click="viewSessionDetail(item)"
            >
              <div class="history-item-header">
                <div class="topic">{{ item.topic }}</div>
                <div class="time">{{ formatDate(item.created_at) }}</div>
              </div>
              
              <div class="history-item-content">
                <div class="positions">
                  <el-tag 
                    :type="item.position === 'pro' ? 'success' : 'danger'"
                    effect="plain"
                    size="small"
                  >
                    {{ item.position === 'pro' ? '正方' : '反方' }} (你)
                  </el-tag>
                  <el-tag 
                    :type="item.position === 'pro' ? 'danger' : 'success'"
                    effect="plain"
                    size="small"
                  >
                    {{ item.position === 'pro' ? '反方' : '正方' }} (AI)
                  </el-tag>
                </div>
                
                <div class="result" v-if="item.result">
                  <span class="result-label">结果:</span>
                  <span :class="getResultClass(item.result)">{{ item.result }}</span>
                </div>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="培训历史" name="training">
          <el-empty v-if="filteredTrainingHistory.length === 0" description="暂无培训历史记录" />
          
          <div v-else class="history-list">
            <el-card 
              v-for="(item, index) in filteredTrainingHistory" 
              :key="index" 
              class="history-item"
              :class="{ 'selected': selectedSession?.id === item.id }"
              @click="viewSessionDetail(item)"
            >
              <div class="history-item-header">
                <div class="topic">{{ item.topic }}</div>
                <div class="time">{{ formatDate(item.created_at) }}</div>
              </div>
              
              <div class="history-item-content">
                <div class="training-type">
                  <el-tag type="info" effect="plain" size="small">
                    {{ item.trainingType }}
                  </el-tag>
                </div>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-drawer
      v-model="drawerVisible"
      direction="rtl"
      size="70%"
      :with-header="false"
      destroy-on-close
    >
      <session-detail
        v-if="selectedSession"
        :session="selectedSession"
        :type="activeTab"
        @close="drawerVisible = false"
      />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import SessionDetail from '../views/SessionDetail.vue'
import { getDebateHistory, getTrainingHistory } from '../services/debateServ'
import type { Session, TrainingSession } from '../models/debate'

// 标签页状态
import type { Ref } from 'vue'
const activeTab: Ref<'debate' | 'training'> = ref('debate')
const searchKeyword = ref('')
const drawerVisible = ref(false)
const selectedSession = ref<Session | TrainingSession | null>(null)

// 历史记录数据
const debateHistory = ref<Session[]>([])
const trainingHistory = ref<TrainingSession[]>([])

// 筛选后的历史记录
const filteredDebateHistory = computed(() => {
  if (!searchKeyword.value) return debateHistory.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return debateHistory.value.filter(item => 
    item.topic.toLowerCase().includes(keyword) ||
    item.result?.toLowerCase().includes(keyword)
  )
})

const filteredTrainingHistory = computed(() => {
  if (!searchKeyword.value) return trainingHistory.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return trainingHistory.value.filter(item => 
    item.topic.toLowerCase().includes(keyword) ||
    item.trainingType.toLowerCase().includes(keyword)
  )
})

// 处理标签页切换
const handleTabClick = () => {
  searchKeyword.value = ''
  selectedSession.value = null
}

// 查看会话详情
const viewSessionDetail = (session: Session | TrainingSession) => {
  selectedSession.value = session
  drawerVisible.value = true
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取结果样式
const getResultClass = (result: string) => {
  if (result.includes('胜')) return 'result-win'
  if (result.includes('败')) return 'result-lose'
  return 'result-draw'
}

// 加载历史记录数据
const loadDebateHistory = async () => {
  try {
    const response = await getDebateHistory()
    debateHistory.value = response.data
    console.log(debateHistory.value)
  } catch (error) {
    ElMessage.error('加载辩论历史记录失败')
    console.error('Failed to load debate history:', error)
  }
}

const loadTrainingHistory = async () => {
  try {
    const response = await getTrainingHistory()
    trainingHistory.value = response
  } catch (error) {
    ElMessage.error('加载培训历史记录失败')
    console.error('Failed to load training history:', error)
  }
}

// 组件挂载时加载数据
onMounted(async () => {
  await loadDebateHistory()
  await loadTrainingHistory()
})
</script>

<style scoped>
.history-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.history-card {
  border-radius: 12px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #303133;
}

.search-input {
  width: 300px;
}

.history-tabs {
  margin-top: 10px;
}

.history-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.history-item {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
  border-left: 4px solid transparent;
}

.history-item:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.history-item.selected {
  border-left-color: #409eff;
  background-color: #f0f9ff;
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.topic {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
  max-width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.time {
  font-size: 13px;
  color: #909399;
}

.history-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.positions, .training-type {
  display: flex;
  gap: 8px;
}

.result {
  font-size: 14px;
}

.result-label {
  color: #909399;
  margin-right: 5px;
}

.result-win {
  color: #67c23a;
  font-weight: 500;
}

.result-lose {
  color: #f56c6c;
  font-weight: 500;
}

.result-draw {
  color: #e6a23c;
  font-weight: 500;
}

@media (max-width: 768px) {
  .history-list {
    grid-template-columns: 1fr;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-input {
    width: 100%;
  }
}
</style>